package de.windeln.marketing.validation;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.joda.time.DateTime;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import de.windeln.marketing.campaign.costinterval.model.CostintervalClientObject;
import de.windeln.marketing.campaign.costinterval.services.interfaces.CostIntervalService;

@Component
public class OverlappingCostIntervals implements Validator{
	
	@Resource(name = "costIntervalService")
	private CostIntervalService costIntervalService;

	@Override
	public boolean supports(Class<?> clazz) {
		return clazz == CostintervalClientObject.class;
	}

	@Override
	public void validate(Object target, Errors errors) {
		CostintervalClientObject cico = (CostintervalClientObject) target;
		List<Map<String, Object>> dates = new ArrayList<Map<String, Object>>();
		dates = costIntervalService.findAllCostintervalDatesByCampaignId(cico.getCampaignId());
//		System.out.println("Dates: " + dates);
//		System.out.println("" + dates.get(0).get("COST_END") + "," + dates.get(0).get("COST_START"));
		for(int i = 0; i < dates.size(); i++){
			DateTime cost_end = new DateTime((Date) dates.get(i).get("COST_END"));
			DateTime cost_start = new DateTime((Date) dates.get(0).get("COST_START"));
			if(!(cost_end.isBefore(new DateTime(cico.getCostStart())) || cost_start.isAfter(new DateTime(cico.getCostEnd())))){
				errors.rejectValue("costStart", "Overlapping Dates", "Cost Interval is overlapping with other Cost Intervals!");
				errors.rejectValue("costEnd", "Overlapping Dates", "Cost Interval is overlapping with other Cost Intervals!");
			}
		}
		

	}

}
